package com.kaifamiao.wendao.servlet;

import com.kaifamiao.wendao.entity.Comment;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.CommentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet( "/comment/publish" )
public class CommentPublishServlet extends HttpServlet {

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        // 应该首先完成数据校验

        HttpSession session = request.getSession();
        // 从会话对象中获取名称是 customer 的属性值
        Customer customer = (Customer)session.getAttribute( "customer" );
        // 检查用户是否已经登录
        if( customer == null ){
            session.setAttribute( "message" , "请先登录" );
            response.sendRedirect( request.getContextPath() + "/customer/sign/in");
            return ;
        }

        // 获取请求参数(即包含在form表单中的数据)
        String tid = request.getParameter( "topicId" );
        String content = request.getParameter( "content" ) ;

        // 获取发布者的IP地址
        String ip = request.getRemoteAddr();

        Comment c = new Comment();
        c.setContent( content );
        c.setPublishIp( ip );

        Topic t = new Topic();
        t.setId( Integer.valueOf( tid ) );
        // 设置评论对应的话题
        c.setTopic( t );
        // 设置评论者
        c.setPublisher( customer );

        CommentService cs = new CommentService();
        // 保存 Comment 到数据库
        cs.save( c );

        // 评论成功后仍然返回到原来的话题页面 ( 1、肯定返回到话题详情页面；2、必须明确是哪个话题 )
        response.sendRedirect( request.getContextPath() + "/topic/detail?id=" + tid );

    }
}
